package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.AddressBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.FormListBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class AddFormActivity extends BaseActivity implements View.OnClickListener {
    private final int FROM_INVOICE_TYPE = 642;
    private final int VALUE_TAX = 895;
    private TextView title;
    private TextView type_name;
    private TextView tv_texture, et_company_shui;
    private View line;
    private RelativeLayout rl_company_name;
    private EditText et_company_name;

    private ImageView iv_head1, iv_head2;
    private ImageView iv_content1, iv_content2, iv_content3;

    private TextView tv_right;
    private EditText ed_phone;

    private String invoiceContent = "明细";//发票内容
    private String fullMessage;
    private TextView tv_noAddress_text;
    public static AppCompatActivity invoiceAct;

    private static final int CODE_ADDRESS = 111;
    private static final int CODE_INVOICE = 112;

    private View include_address, include_noAddress;
    private TextView tv_name, tv_phone, tv_address, tv_company_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_form);
        EventBus.getDefault().register(this);
        invoiceAct = this;
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }

    private int titletype = 0;

    private void initView() {
        ed_phone = (EditText) findViewById(R.id.ed_phone);
        tv_noAddress_text = (TextView) findViewById(R.id.tv_noAddress_text);
        tv_noAddress_text.setText("请填写发票寄往地址");
        tv_company_name = (TextView) findViewById(R.id.tv_company_name);
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("发票");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.submit).setVisibility(View.VISIBLE);
        findViewById(R.id.submit).setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.submit);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("保存");
        tv_right.setTextColor(0xff008c99);
        findViewById(R.id.rl_choose_type).setOnClickListener(this);//选择类型
//        findViewById(R.id.rl_add_address).setOnClickListener(this);//选择地址
        type_name = (TextView) findViewById(R.id.tv_invoice_name);//类型名字
        tv_texture = (TextView) findViewById(R.id.tv_texture);//材质

        findViewById(R.id.rl_personage).setOnClickListener(this);//个人
        findViewById(R.id.rl_company).setOnClickListener(this);//单位
        iv_head1 = (ImageView) findViewById(R.id.iv_head1);
        iv_head2 = (ImageView) findViewById(R.id.iv_head2);

        line = findViewById(R.id.line);//线
        rl_company_name = (RelativeLayout) findViewById(R.id.rl_company_name);//单位名称布局
        et_company_name = (EditText) findViewById(R.id.et_company_name);//单位名称填写
        et_company_shui = (EditText) findViewById(R.id.et_company_shui);//税号

        findViewById(R.id.rl_particular).setOnClickListener(this);//明细
        findViewById(R.id.rl_work).setOnClickListener(this);//办公用品
        findViewById(R.id.rl_cost).setOnClickListener(this);//耗材
        iv_content1 = (ImageView) findViewById(R.id.iv_content1);
        iv_content2 = (ImageView) findViewById(R.id.iv_content2);
        iv_content3 = (ImageView) findViewById(R.id.iv_content3);

        /**
         * 判断是否有地址选择显示隐藏的布局
         */
        include_address = findViewById(R.id.include_choose_address);//有地址
        include_noAddress = findViewById(R.id.include_choose_noAddress);//无收货地址

        include_address.setOnClickListener(this);
        include_noAddress.setOnClickListener(this);

        include_address.setVisibility(View.GONE);// TODO  暂时设为不可见

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_address = (TextView) findViewById(R.id.tv_address);


        if (isUpdate == 1) {
            try {
                titletype = Integer.parseInt(info1.getTitle_type());
            } catch (Exception e) {
                titletype = 0;
            }
            invoiceContent = info1.getInvoice_detail();
            et_company_name.setText(info1.getInvoice_title());
            et_company_shui.setText("" + info1.getInvoice_taxpayer_id());
            include_address.setVisibility(View.VISIBLE);
            include_noAddress.setVisibility(View.GONE);
            tv_name.setText(info1.getGet_consignee());
            tv_phone.setText(info1.getGet_tel());
            tv_address.setText(info1.getGet_province() + "" + info1.getGet_city() + "" + info1.getGet_district());
            receiptAddrId = info1.getAddress_id();
        }
        if (titletype == 1) {
            titletype = 1;
            iv_head2.setImageResource(R.mipmap.ic_choose_li);
            iv_head1.setImageResource(R.mipmap.ic_choose_nor);
        } else {
            titletype = 0;
            iv_head1.setImageResource(R.mipmap.ic_choose_li);
            iv_head2.setImageResource(R.mipmap.ic_choose_nor);
        }
        if (invoiceContent.equals("明细")) {
            iv_content1.setImageResource(R.mipmap.ic_choose_li);
            iv_content2.setImageResource(R.mipmap.ic_choose_nor);
            iv_content3.setImageResource(R.mipmap.ic_choose_nor);
        } else if (invoiceContent.equals("办公用品")) {
            iv_content2.setImageResource(R.mipmap.ic_choose_li);
            iv_content1.setImageResource(R.mipmap.ic_choose_nor);
            iv_content3.setImageResource(R.mipmap.ic_choose_nor);

        } else if (invoiceContent.equals("耗材")) {
            iv_content3.setImageResource(R.mipmap.ic_choose_li);
            iv_content1.setImageResource(R.mipmap.ic_choose_nor);
            iv_content2.setImageResource(R.mipmap.ic_choose_nor);
        }
    }


    private int isUpdate;
    private String id;

    private void initData() {
        isUpdate = getIntent().getIntExtra("isUpdate", 0);
        if (isUpdate == 1) {
            id = getIntent().getStringExtra("id");
            getData();
        } else {
            initView();
        }
    }

    private FormListBean.InfoEntity info1 = new FormListBean.InfoEntity();

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("id", id);
        showDialog();
        XUtil.Post(Url.INVOICE_DETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        info1 = gson.fromJson(info, FormListBean.InfoEntity.class);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                initView();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //保存
            case R.id.submit:
                String text = et_company_name.getText().toString();
                if (null != text && !"".equals(text) && !"".equals(receiptAddrId) && null != receiptAddrId) {
                    getResultAndFinishActivity(fullMessage, receiptAddrId, "1", "", text, invoiceContent);
                } else if ("".equals(text)) {
                    MyToast("请填写名称");
                } else if ("".equals(receiptAddrId) || tv_noAddress_text.getText().equals("请填写发票寄往地址")) {
                    MyToast("请选择收发票地址");
                } else if (null == receiptAddrId) {
                    MyToast("请选择收发票地址");
                }
                break;

            //选择类型
            case R.id.rl_choose_type:
                intent = new Intent(this, InvoiceTypeActivity.class);
                startActivityForResult(intent, FROM_INVOICE_TYPE);
                break;

            //有地址，前去修改
            case R.id.include_choose_address:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //无地址，添加收货地址
            case R.id.include_choose_noAddress:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //个人
            case R.id.rl_personage:
                titletype = 0;

                iv_head1.setImageResource(R.mipmap.ic_choose_li);
                iv_head2.setImageResource(R.mipmap.ic_choose_nor);
//                line.setVisibility(View.GONE);
//                rl_company_name.setVisibility(View.GONE);
                tv_company_name.setText("个人名称");
                break;

            //单位
            case R.id.rl_company:
                titletype = 1;
                tv_company_name.setText("单位名称");
                iv_head1.setImageResource(R.mipmap.ic_choose_nor);
                iv_head2.setImageResource(R.mipmap.ic_choose_li);
//                line.setVisibility(View.VISIBLE);
//                rl_company_name.setVisibility(View.VISIBLE);
                break;

            //明细
            case R.id.rl_particular:
                invoiceContent = "明细";

                iv_content1.setImageResource(R.mipmap.ic_choose_li);
                iv_content2.setImageResource(R.mipmap.ic_choose_nor);
                iv_content3.setImageResource(R.mipmap.ic_choose_nor);
                break;

            //办公用品
            case R.id.rl_work:
                invoiceContent = "办公用品";

                iv_content1.setImageResource(R.mipmap.ic_choose_nor);
                iv_content2.setImageResource(R.mipmap.ic_choose_li);
                iv_content3.setImageResource(R.mipmap.ic_choose_nor);
                break;

            //耗材
            case R.id.rl_cost:
                invoiceContent = "耗材";

                iv_content1.setImageResource(R.mipmap.ic_choose_nor);
                iv_content2.setImageResource(R.mipmap.ic_choose_nor);
                iv_content3.setImageResource(R.mipmap.ic_choose_li);
                break;
            default:
                break;
        }
    }

    private String typeName;
    private String receiptAddrId;//发票收货地址id
    private String invoiceTitle;
    private String taxpayerId;
    private String bank;
    private String bankAccount;
    private String address;
    private String phone;
    private String type1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FROM_INVOICE_TYPE:
                if (resultCode == RESULT_OK) {
                    typeName = data.getExtras().getString("result");
                    invoiceTitle = data.getExtras().getString("invoiceTitle");
                    taxpayerId = data.getExtras().getString("taxpayerId");
                    bank = data.getExtras().getString("bank");
                    bankAccount = data.getExtras().getString("bankAccount");
                    address = data.getExtras().getString("address");
                    phone = data.getExtras().getString("phone");
                    type1 = data.getExtras().getString("type1");
                    //type_name.setText(typeName);

                    getResultAndFinishActivity1(typeName, invoiceTitle, taxpayerId, bank, bankAccount, address, phone, type1);
                }
                break;

            //地址回调
            case CODE_ADDRESS:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
                        AddressBean addressBean = (AddressBean) data.getSerializableExtra("addressBean");
                        include_address.setVisibility(View.VISIBLE);
                        include_noAddress.setVisibility(View.GONE);
                        String province = addressBean.getProvince();
                        String city = addressBean.getCity();
                        String district = addressBean.getDistrict();
                        String place = addressBean.getPlace();
                        String addr = province + city + district + place;
                        tv_name.setText(addressBean.getConsignee());
                        tv_phone.setText(addressBean.getTelephone());
                        tv_address.setText(addr);
                        receiptAddrId = addressBean.getAddress_id();
                    }
                }
                break;

            default:
                break;
        }
    }


    public void getResultAndFinishActivity(String name, String receiptAddrId, String invoiceType2, String invoiceHeader, String company, String receiptType) {
        if (et_company_name.getText().toString().trim().equals("")) {
            MyToast("请填写名称");
            return;
        }
/**
 * Member/addInvoice()新增发票
 参数token,
 type：发票类型：1：普通，2：增值
 invoice_title：发票抬头
 invoice_company 发票公司
 invoice_taxpayer_id 纳税人识别号
 invoice_address 发票地址
 invoice_phone 发票电话
 invoice_bank 开户银行
 invoice_bank_account 开户账号
 invoice_detail 发票明细(明细、办公用品、耗材)
 get_consignee 收货人
 get_tel 电话
 get_address 地址
 get_province省
 get_city市
 get_district区
 default 1为默认，0不默认

 */

        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", 1);
        map.put("invoice_title", et_company_name.getText().toString().trim());
        map.put("address_id", receiptAddrId);
        map.put("invoice_detail", invoiceContent);
        map.put("titletype", titletype);

        if (!TextUtils.isEmpty(et_company_shui.getText().toString())) {
            map.put("invoice_taxpayer_id", et_company_shui.getText().toString());
        }

//        map.put("invoice_taxpayer_id", invoice_title);
//        map.put("invoice_phone", ed_phone.getText().toString().trim());
//        map.put("invoice_bank", invoice_title);
//        map.put("invoice_bank_account", invoice_title);
//        map.put("get_consignee", invoice_title);
//        map.put("get_tel", invoice_title);
//        map.put("get_address", invoice_title);
//        map.put("get_province", invoice_title);
//        map.put("get_city", invoice_title);
//        map.put("get_district", invoice_title);
//        map.put("default", invoice_title);
        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }
        String url = Url.ADDINVOICE;
        if (isUpdate == 1) {
            map.put("id", id);
            url = Url.EDITINVOICE;
        }

        XUtil.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });


    }

    public void getResultAndFinishActivity1(String name, String invoiceTitle, String taxpayerId,
                                            String bank, String bankAccount, String address,
                                            String phone, String type1) {
        Intent intent = new Intent();
        intent.putExtra("InvoiceResult", name);
        intent.putExtra("invoiceTitle", invoiceTitle);
        intent.putExtra("taxpayerId", taxpayerId);
        intent.putExtra("bank", bank);
        intent.putExtra("bankAccount", bankAccount);
        intent.putExtra("address", address);
        intent.putExtra("phone", phone);
        intent.putExtra("type1", type1);
        setResult(VALUE_TAX, intent);
        finish();

    }
}
